<?php

class Admin_LoginController extends GTL_Action {

    public function init() {
        parent::init();
        $this->_helper->layout()->setLayout('admin-login');
        $this->sessionName = Zend_Registry::get('sessionName');
        $auth = Zend_Auth::getInstance();
        $this->view->LoggedIn = $auth->hasIdentity();
        $defaultSession = new Zend_Session_Namespace($this->sessionName);
        $defaultSessionVal = $defaultSession->getIterator();
        if (isset($defaultSessionVal['storage']) && !empty($defaultSessionVal['storage'])) {
            $this->view->user = $defaultSessionVal['storage'];
            $this->view->loggedinUserId = $this->view->user->usr_id;
            $this->_helper->redirector('index', 'index', 'admin');
        }
        /* Initialize action controller here */
    }

    public function indexAction() {
        
        $loginForm = new Form_Admin_Login();
        $this->view->form = $loginForm;
        $errorMessage = Array();

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            if (!$loginForm->isValid($postedData)) {
                $errorMessage = $loginForm->getMessages();
            } else {
                $auth = Zend_Auth::getInstance();
                $adapter = GTL_Common::getAuthAdapter($postedData, 'default');
                $result = $auth->authenticate($adapter);
                if ($result->isValid()) {
                    $auth->getStorage();
                    $objUser = $adapter->getResultRowObject();
                    $auth->setStorage(new Zend_Auth_Storage_Session($this->sessionName));
                    $auth->getStorage()->write($objUser);
					$this->_helper->redirector('index', 'index', 'admin');
                } else {
                    $loginForm->addErrorMessage("Username and Password do not match.");
                    $errorMessage['0'] = $loginForm->getErrorMessages();
                }
            }
        }
        $this->view->errorMessage = $errorMessage;
    }

  
    public function forgotpasswordAction() {

        $frgtPwdForm = new Form_Admin_Forgotpassword();
        $this->view->form = $frgtPwdForm;
        $errorMessage = Array();
        $successmessage = "";
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            if (!$frgtPwdForm->isValid($postedData)) {
                $errorMessage = $frgtPwdForm->getMessages();
            } else {
                $model = new Model_Login();
                $usrArray = $model->checkEmailForForgotPassword($postedData['email']);
                if (empty($usrArray) || $usrArray['lgn_id'] == '') {
                    $frgtPwdForm->addErrorMessage("Email address is not registered.");
                    $errorMessage['0'] = $frgtPwdForm->getErrorMessages();
                } else {
                    $actualPassword = GTL_Common::generatePassword(9, 2);
                    $md5_password = md5($actualPassword);
                    $body = "
				<html>
				<head>
				</head>
				<body>
				<table style='width:50%'>
				    <tr>
				    <td>
				    <p>Hello user</p>
				    <p>New password for your " . $this->config->SITE_NAME . " admin!</p>
				    <table border='1' cellpadding='10'>
					    <tr>
						    <td>Email Address</td>
						    <td width='80px' align='center'>" . $usrArray['lgn_email'] . "</td>
					    </tr>
					    <tr>
						    <td>Password</td>
						    <td>" . $actualPassword . "</td>
					    </tr>
				    </table>
				    <p>
				    Thanks,<br/>
				    The Admin Team
				    </p>
				     </td>
				    </tr>
				</table>
				</body>
				</html>
				";

				$metaDataModel = new Model_Metadata();
				$ADMIN_MAIL_DATA = $metaDataModel->fetchEntryByKey("ADMIN_FROM_EMAIL");
				$ADMIN_MAIL = $ADMIN_MAIL_DATA['mtd_value'];
				
				$ADMIN_FROM_DATA = $metaDataModel->fetchEntryByKey("ADMIN_FROM_NAME");
				$ADMIN_FROM = $ADMIN_FROM_DATA['mtd_value'];
				
				$mail = new Zend_Mail();
				$mail->setBodyText($body);
				$mail->setBodyHtml($body, "iso-8859-1");
				$mail->addTo($ADMIN_MAIL, $ADMIN_FROM);
				$mail->setReplyTo($ADMIN_MAIL, $ADMIN_FROM);
				$mail->addTo($usrArray['lgn_email'], $ADMIN_FROM);
				$mailSubject = "Forgot Password Request";
				$mail->addHeader('MIME-Version', '1.0');
				$mail->addHeader('Content-Transfer-Encoding', '8bit');
				$mail->addHeader('X-Mailer:', 'PHP/' . phpversion());
				$mail->setSubject($mailSubject);

				try {
					$mail->send();
					$dataUpdate = array();
					$dataUpdate['lgn_id'] = $usrArray['lgn_id'];
					$dataUpdate['lgn_password'] = $md5_password;
					$model->save($dataUpdate, 'lgn_id');
					$frgtPwdForm->reset();
					$successmessage = "New password is sent to your email.";
				} catch (Zend_Exception $e) {
					$frgtPwdForm->addErrorMessage("Due to technical problem, email has not been sent. Please try later or contact webmaster.");
					$errorMessage['0'] = $frgtPwdForm->getErrorMessages();
				}
				$frgtPwdForm->reset();
                }
            }
        }

        $this->view->successmessage = $successmessage;
        $this->view->errorMessage = $errorMessage;
    }

}

?>